/*
  @author hcao
  @date 2016/11/14
  @desc 所有业务逻辑
  
 */

$(function() {
	 //所有弹窗的关闭
	$(".commod_close").click(function() {
		timer2 = setInterval(autoTime, 100);
		$(this).parent().fadeOut('fast')
		$(".background").fadeOut('fast')
		$('html ,body').css({
			overflow: 'initial',
			height: '100%'
		})
		$(".selection li").css({
			"backgroundColor": "#ededed"
		})
	})

	//我的奖品
	$(".js_my_award").on('click', function() {
		var html = ''; //页面文本
		var str = ''; //页面信息为空
		$('.list ul').html("");
		$.ajax({ //获取我的奖品
			type: "get",
			url: "index.php?a=myPrize&id=" + $("#user_id").val(),
			async: true,
			dataType: 'json',
			success: function(restlt) {
				if(restlt.status == 1) {
					for(var j = 0; j < restlt.msg.length; j++) {
						html += '<li><div class="left">' + restlt['msg'][j]['prize_title'] + '</div><div class="right">' + restlt['msg'][j]['prize_name'] + '</div></li>';
					}
					$('.list ul').html(html);
				} else {
					str = '<div class="img"><img src="img/meiyoujiangpin.png"/></div>'
					$('.list ul').html(str);
				}
			}
		})
		$('.my_award_list').fadeIn('fast')
		$(".background").fadeIn('fast')
		$('html,body').css({
			'overflow': 'hidden',
			'height': '100%'
		})
	})

	//比赛规则
	$(".js_activity_rule").click(function() {
		$('#activity_rule').fadeIn('fast')
		$(".background").fadeIn('fast')
		$('html,body').css({
			'overflow': 'hidden',
			'height': '100%'
		})
	})
	$(".js_rule_more").click(function() {
		$.ajax({
			type: "get",
			url: "index.php?a=_addButtonLog&name=rule",
			async: true,
			dataType: 'json',
			success: function(restlt) {

			}
		})
		$('#activity_rule').hide()
		$("#activity_rule_two").show()
	})

	//排行榜
	$(".js_ranking_list").click(function() {
		$('.js_list').html("");
		var html = '<table cellspacing="0" cellpadding="" id="ranking_list"><tr><th>排名</th><th>手机号</th><th>耗时</th><th>称号</th></tr>';
		$.ajax({
			type: "get",
			url: "index.php?a=rankingList",
			async: true,
			dataType: 'json',
			success: function(restlt) {
				if(restlt.status == 1) {
					var title = ""; //记录称号
					for(var i = 0; i < restlt.msg.length; i++) {
						//根据时间判断称号
						if(restlt['msg'][i]['the_shortest_time'] <= 150) {
							title = '学霸';
						} else if(restlt['msg'][i]['the_shortest_time'] > 150 && restlt['msg'][i]['the_shortest_time'] <= 250) {
							title = '学神';
						} else if(restlt['msg'][i]['the_shortest_time'] > 250 && restlt['msg'][i]['the_shortest_time'] <= 350) {
							title = '学民';
						} else {
							title = '学渣';
						}
						//判断前三名
						if(i == 0) {
							html += '<tr><td><img src="img/paihangbang1.png"/></td><td>' + restlt['msg'][i]['tel'] + '</td><td>' + restlt['msg'][i]['the_shortest_time'] + 's</td><td>' + title + '</td></tr>';
						} else if(i == 1) {
							html += '<tr><td><img src="img/paihangbang2.png"/></td><td>' + restlt['msg'][i]['tel'] + '</td><td>' + restlt['msg'][i]['the_shortest_time'] + 's</td><td>' + title + '</td></tr>';
						} else if(i == 2) {
							html += '<tr><td><img src="img/paihangbang3.png"/></td><td>' + restlt['msg'][i]['tel'] + '</td><td>' + restlt['msg'][i]['the_shortest_time'] + 's</td><td>' + title + '</td></tr>';
						} else {
							html += '<tr><td>' + (parseInt(i) + parseInt(1)) + '</td><td>' + restlt['msg'][i]['tel'] + '</td><td>' + restlt['msg'][i]['the_shortest_time'] + 's</td><td>' + title + '</td></tr>';
						}
					}
					$('.js_list').append(html + '</table>');
				} else {
					var str = '<div class="img"><img src="img/meiyoupaiming.png"/></div>';
					$('.js_list').append(str);
				}
			}
		})
		$('.ranking').fadeIn('fast')
		$(".background").fadeIn('fast')
		$('html,body').css({
			'overflow': 'hidden',
			'height': '100%'
		})
	})

	//活动结束
	$(".js_begin a").click(function(event) {
		alert("活动已结束");
		event.preventDefault();
	});
	//选择关卡
	$(".select_question li").on('click', function() {
		var has = $(this).attr('class')
		if(has != 'hasselect') {
			$.ajax({
				type: "get",
				url: "index.php?a=_addButtonLog&name=question" + this.id,
				async: true,
				dataType: 'json',
				success: function(restlt) {

				}
			})
			window.location.href = 'index.php?a=question&question_id=' + this.id + '&id=' + $('#user_id').val();
		}
	})

	//开始答题
	var time = 0;
	var timer = timer2 = null;
	timer2 = setInterval(autoTime, 100);

	function autoTime() { //自动计时方法
		clearInterval(timer)
		time += 0.1;
		var allTime = time.toFixed(1)
		$("#time").html(allTime + 's');
		if(time > 999.9) {
			$("#time").html(999.9 + 's');
			$(".js_chaoshi").fadeIn('fast')
			$(".background_two").fadeIn('fast')
		}
	}
	$(".js_back").click(function() {
		window.location.href = "index.php?a=remainingLevel&id=" + $('#user_id').val();
	})
	
	//点击选项
	$(".selection li").on('click', function() {
		var result = $(this).attr('class') //正确的答案
		var arr = $("#number").html().split('/') //当前的提数
		var val = arr[0]; //题数
		var next_question = 0;
		if(val == 1 && $('#status').val() == 1) {
			$.ajax({
				type: "get",
				url: "index.php?a=changeLevelSurplus&question_id=" + $('#question_id').val() + "&id=" + $('#user_id').val(),
				async: true,
				dataType: 'json',
				success: function(restlt) {
					if(restlt.status == 0) {//错误处理
						clearInterval(timer2);
						$(".have_success").html('网络超时').show()
					}
				}
			})
		}
		if(result == 'right') { //回答正确
			var endtime = $("#time").html().toString();
			$(this).css({
					"backgroundColor": "#8cc768"
			})
			if(val == '10') {//闯关成功
				if(endtime.substring(0, endtime.length - 1) <= 150) {
					//更改闯关成功领取状态
					$.ajax({
						type: "get",
						url: "index.php?a=changeDrawStatus&draw_status=1&id=" + $('#user_id').val(),
						async: true,
						dataType: 'json',
						success: function(restlt) {
							if(restlt.status == 1) {
								window.location.href = 'index.php?a=enterSuccessfully&time=' + endtime + '&id=' + $('#user_id').val() + '&question_id=' + $('#question_id').val();
							} else {//错误处理
								alert("网络异常！");
							}
						},
						error: function(XMLHttpRequest, textStatus, errorThrown) {
							alert(errorThrown);
						}
					})
				} else { //继续闯关
					window.location.href = 'index.php?a=enterSuccessfully&time=' + endtime + '&id=' + $('#user_id').val() + '&question_id=' + $('#question_id').val();
				}
			} else {//闯关失败
				for(var i = 1; i < 11; i++) {
					$("#question" + i).css('display', 'none');
				}
				next_question = parseInt(val) + parseInt(1);
				$("#question" + next_question).css('display', 'block');
				$("#number").html(next_question + '/10');
			}

		} else { //回答错误
			$('#status').val(0);
			clearInterval(timer2); //时间暂停
			time = parseInt($("#time").html()) + 20; //回答错误时间加20s
			$('.err' + val).fadeIn('fast')
			$(".background").fadeIn('fast')
			$('body ,html').css({
				'overflow': 'hidden',
				'height': '100%'
			})
			$(this).css({
				"backgroundColor": "#ed7366"
			})
		}

	})

	//领取奖品
	$(".js_my_get").click(function() {
		if($('.js_total_time').html() <= 150) { //更具回答的总时间判断奖励<150有奖励
			$.ajax({
				type: "get",
				url: "index.php?a=getDrawStatus&id=" + $('#user_id').val(),
				async: true,
				dataType: 'json',
				success: function(restlt) {
					//成功
					if(restlt.status == 1) {
						$.ajax({
							type: "get",
							url: "index.php?a=checkEnter&id=" + $('#user_id').val() + "&award_type=" + $('#question_id').val() + "-1-" + $('.chenghao').html().replace(/(^\s*)|(\s*$)/g, ""),
							async: true,
							dataType: 'json',
							success: function(restlt) {
								if(restlt.status == 2) {
									$('#award_type').val(1);
									$(".background").fadeIn('fast')
									$(".user_info").fadeIn('fast')
								} else if(restlt.status == 1) {
									//更改闯关成功后的领取状态
									$.ajax({
										type: "get",
										url: "index.php?a=changeDrawStatus&draw_status=0&id=" + $('#user_id').val(),
										async: true,
										dataType: 'json',
										success: function(restlt) {
											if(restlt.status == 1) {
												$(".have_success").fadeIn('fast')
												setTimeout(function() {
													$(".have_success").hide()
												}, 2000)
											}
										}
									})
								} else {
									//错误处理
									$(".have_success").html('网络超时').show()
									setTimeout(function() {
										$(".have_success").hide()
									}, 1500)
								}
							}
						})
					} else { //已经领取过奖品
						$(".have_success").html("您已经领取过了！").show();
						setTimeout(function() {
							$(".have_success").hide()
						}, 1500)
					}

				}
			});
		} else {//更具回答的总时间判断奖励  >150没有奖励
			$(".have_success").html("很遗憾，您未获得学霸称号，请继续努力!").show();
			setTimeout(function() {
				$(".have_success").hide()
			}, 1500)
		}

	})

	//用户信息的判断
	var regStr1 = /^[a-z|A-Z|\u4E00-\u9FFF]*$/; //用户姓名
	var reg1 = new RegExp(regStr1);
	var regStr2 = /^1[3578][0-9]{9}$/; //手机号码
	var reg2 = new RegExp(regStr2);
	var trueName = false,
		trueNum = false;  //记录匹配结束后的状态

	$(".userName").on('blur', function() { //失焦 匹配用户姓名
		var userName = $(".userName").val();
		if(userName === '') {
			$(".errName").css({
				color: "red",
				opacity: "1"
			})
			trueName = false;
		} else if(!reg1.test(userName)) {
			$(".errName").html(
				'请输入正确的姓名'
			).css({
				color: "red",
				opacity: "1"
			})
			trueName = false;
		} else {
			$(".errName").css({
				color: "#fff",
				opacity: "0"
			})
			trueName = true; //记录姓名成功状态
		}

	})

	$(".userNum").on('blur', function() {//失焦 匹配用户手机号码
		var userNum = $(".userNum").val();
		if(userNum === '') {
			$(".errNum").css({
				color: "red",
				opacity: "1"
			})
			trueNum = false;
		} else if(!reg2.test(userNum)) {
			$(".errNum").html(
				'请输入正确的号码'
			).css({
				color: "red",
				opacity: "1"
			})
			trueNum = false;
		} else {
			$(".errNum").css({
				color: "#fff",
				opacity: "0"
			})
			trueNum = true; //记录手机号码成功状态
		}
	})
	//提交姓名,号码时进行判断
	$(".js_liang").click(function() {
		var userName = $(".userName").val();
		var userNum = $(".userNum").val();
		if(userName === '') { //姓名错误
			$(".errName").css({
				color: "red",
				opacity: "1"
			})
		}
		if(userNum === '') {//号码错误
			$(".errNum").css({
				color: "red",
				opacity: "1"
			})
		}
		//信息填写正确,去下一题
		if(trueNum && trueName) {
			var id = $('#user_id').val();
			var url = window.location.href;
			if(url.match(/a=enterSuccessfully/g) == 'a=enterSuccessfully') {
				url = "index.php?a=saveAwardEnter&award_type=" + $('#question_id').val() + "-" + $('#award_type').val() + "-" + $('.chenghao').html().replace(/(^\s*)|(\s*$)/g, "") + "&id=" + id + "&name=" + userName + "&tel=" + userNum;
			} else {
				url = "index.php?a=saveAwardEnter&award_type=" + $('#question_id').val() + "-" + $('#award_type').val() + "&id=" + id + "&name=" + userName + "&tel=" + userNum;
			}

			//通过ajax将数据传给后端,
			$.ajax({
				type: "get",
				url: url,
				async: true,
				dataType: 'json',
				success: function(restlt) {
					//成功
					if(restlt.status == 1) {
						if($('#award_type').val() == 1) {
							//更改闯关成功后的领取状态
							$.ajax({
								type: "get",
								url: "index.php?a=changeDrawStatus&draw_status=0&id=" + $('#user_id').val(),
								async: true,
								dataType: 'json',
								success: function(restlt) {
									if(restlt.status == 1) {
										$(".user_info").fadeOut('fast')
										$(".background").fadeOut('fast')
										$(".have_success").show()
										setTimeout(function() {
											$(".have_success").hide()
										}, 2000)
									}
								}
							})
						} else {
							$(".background").fadeOut('fast')
							$(".user_info").fadeOut('fast')
							$(".share-background").fadeOut('fast')
							$(".have_success").html('已成功领取10元免费通用课程!').show()
							setTimeout(function() {
								$(".have_success").hide()
							}, 2000)
						}

					} else {
						//错误处理
						$(".have_success").html('网络超时').show()
						setTimeout(function() {
							$(".have_success").hide()
						}, 1500)
					}

				}
			});
		}
	})

	//闯关成功继续闯关
	$(".js_contiue_three").click(function() {
		$(this).parent().parent().hide()
		$(".js_new_question_one").show();
	})

	//闯关成功按错了
	$(".js_errend_1").click(function() {
		$('#award_type').val(1);
		$(this).parent().parent().hide()
		$(".user_info").fadeIn('fast')
	})

	//不领取;
	$(".js_cancle_1").click(function() {
		var url = window.location.href;
		if(url.match(/a=enterSuccessfully/g) == 'a=enterSuccessfully') {
			if($('#award_type').val() == 2) {
				$(this).parent().parent().hide()
				$(".background").fadeOut('fast')
			} else {
				$.ajax({
					type: "get",
					url: "index.php?a=changeDrawStatus&draw_status=0&id=" + $('#user_id').val(),
					async: true,
					dataType: 'json',
					success: function(restlt) {
						if(restlt.status == 1) {
							window.location.href = 'index.php?a=remainingLevel&id=' + $('#user_id').val();
						} else {
							//错误处理
							$(".have_success").html('网络超时').show()
							setTimeout(function() {
								$(".have_success").hide()
							}, 1500)
						}
					}
				})
			}
		} else {
			$(this).parent().parent().hide()
			$(".background").fadeOut('fast')
		}

	})

	//我要分享
	$(".js_share").click(function() {
		$('.share').html("");
		var img = ""; //判断用户是否分享过,
		
		//检测是否已经领取过分享奖励
		$.ajax({
			type: "get",
			url: "index.php?a=checkShare&id=" + $('#user_id').val(),
			async: true,
			dataType: 'json',
			success: function(restlt) {
				if(restlt.status == 1) {
					img = '<img src="img/share2.png" />'; //已经分享过
				} else {
					img = '<img src="img/share.png" />'; //还没有分享
				}
				$('.share').append(img);
			}
		})
		$(".share").fadeIn('fast')
		$('.share-background').fadeIn('fast')
		$('html,body').css({
			overflow: 'hidden',
			height: '100%'
		})
	})

	//从新选题
	$(".js_new_question").click(function() {
		//获取闯关成功后的领取状态
		$.ajax({
			type: "get",
			url: "index.php?a=getDrawStatus&id=" + $('#user_id').val(),
			async: true,
			dataType: 'json',
			success: function(restlt) {
				if(restlt.status == 1) {
					$(".background").fadeIn('fast');
					$(".js_new_question_two").show();
				} else if(restlt.status == 0) {
					window.location.href = 'index.php?a=remainingLevel&id=' + $('#user_id').val();
				} else {
					//错误处理
					$(".have_success").html('网络超时').show()
					setTimeout(function() {
						$(".have_success").hide()
					}, 1500)
				}
			}
		})
	})

	//重新选题，按钮“否”
	$(".js_no").click(function() {
		$(".background").fadeOut('fast');
		$(".js_new_question_two").fadeOut('fast');
	})

	//重新选题，按钮“是”
	$(".js_yes").click(function() {
		$.ajax({
			type: "get",
			url: "index.php?a=changeDrawStatus&draw_status=0&id=" + $('#user_id').val(),
			async: true,
			dataType: 'json',
			success: function(restlt) {
				if(restlt.status == 1) {
					window.location.href = 'index.php?a=remainingLevel&id=' + $('#user_id').val();
				} else {
					//错误处理
					$(".have_success").html('网络超时').show()
					setTimeout(function() {
						$(".have_success").hide()
					}, 1500)
				}
			}
		})
	})
})